# coding:utf-8
import os
import datetime
import random
from finance_c2c.settings import BASE_DIR
from core.tools.edit_photo import EditPicture


def upload_file(file_obj, relation_path=''):
    """
    :param relation_path: 相对路径
    :param file_obj: 文件对象
    :return:
    """
    absolute_path = os.path.join(BASE_DIR, 'c2c_media', relation_path)
    EditPicture.make_dir(absolute_path)
    last_name = file_obj.name.split('.')[1]
    file_name = datetime.datetime.now().strftime("%Y%m%d%H%M%S") + str(random.randint(1, 1000)) + last_name
    file_path = os.path.join(absolute_path, file_name)
    with open(file_path, 'wb') as f:
        for chunk in file_obj.chunks():
            f.write(chunk)
    return file_path


def save_file(content, file_name, relation_path=""):
    """
    保存 BytesIO 文件
    :param content:
    :param relation_path:
    :param file_name:
    :return:
    """
    absolute_path = os.path.join(BASE_DIR, 'c2c_media', relation_path)
    EditPicture.make_dir(absolute_path)
    file_path = os.path.join(absolute_path, file_name)
    content.save(file_path)
    return file_path
